package com.minelx.sqlstructures.statements.parse.select;

import com.minelx.sequence.core.StringScanner;
import com.minelx.sequence.core.ReturnMatcher;
import com.minelx.sqlstructures.common.parse.StringMatcher;
import com.minelx.sqlstructures.statements.clause.Field;

import java.util.function.IntPredicate;

public class FieldMatcher implements ReturnMatcher<Field, StringScanner> {
	private static final String AS = "AS";

	private static final char UNDERSCORE = '_';

	private static final char STAR = '*';

	private static final char DOT = '.';

	private static final IntPredicate FIELD_NAME = character -> Character.isAlphabetic(character) ||
			Character.isDigit(character) ||
			character == '"' ||
			character == UNDERSCORE ||
			character == STAR ||
			character == DOT;

	// FIXME 2021/7/5  wait for me!!!
	@Override
	public Field onMatched(StringScanner source) {
		String fieldName = source.collect(FIELD_NAME);
		source.trim();
		if (source.pass(AS)) {
			source.trim();
			String as = new StringMatcher().get(source).orElseThrow(RuntimeException::new);
			return Field.as(fieldName, as.substring(1, as.length() - 1));
		}
		return Field.of(fieldName);
	}

	@Override
	public boolean isMatch(StringScanner source) {
		return source.existsIf(FIELD_NAME);
	}
}
